//sessionStorage.setItem("userId","193114475332300122"); 
//sessionStorage.setItem("name","任丽琴");
//sessionStorage.setItem("jobnumber","009028");
//sessionStorage.setItem("deptId","55088496");
//sessionStorage.setItem("mobile","18334724145");
var layer;
var longitude,latitude,address;
//var longitude="112.546997";
//var latitude="37.862444";
var date = getDay(0);  //今日
var jobnumber = sessionStorage.getItem("jobnumber")==null?"0":sessionStorage.getItem("jobnumber");
var job = sessionStorage.getItem("job")==null?"0":sessionStorage.getItem("job");
var corp = GetQueryString('corp')==null?"":GetQueryString('corp');
if(corp==''){
	corp = sessionStorage.getItem("corp");
}else{
	sessionStorage.setItem("corp",corp);
}
layui.use(['form','layer'], function(){
	layer = layui.layer;
	
//	dingwei();
});
var _config ;
$.ajax({
	type : "post",
	data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":corp}),
	contentType: "application/json; charset=utf-8",
	async: false,
	url : "../../dingding/getconfig",
	dataType : "json",
	success : function(suc) {
		_config = suc.config;
	}
}); 
dd.config({
	agentId : _config.agentid,
	corpId : _config.corpId,
	timeStamp : _config.timeStamp,
	nonceStr : _config.nonceStr,
	signature : _config.signature,
	jsApiList : [ 'device.geolocation.get','biz.map.locate','biz.map.view','biz.map.search','biz.util.uploadImageFromCamera' ]
});
dd.ready(function() {
	//获取位置
    dd.device.geolocation.get({
		    targetAccuracy : 200,
		    coordinate : 1,
		    withReGeocode : true,
		    useCache:false, //默认是true，如果需要频繁获取地理位置，请设置false
		    onSuccess : function(result) {
			_result = result;
			latitude = _result.latitude;
			longitude = _result.longitude;
			address = _result.address;
			dingwei();

		    },
		    onFail : function(err) {
				alert(JSON.stringify(err));
			}
		});
    
});
if(sessionStorage.getItem("name")){
	onload();
}else{
	dd.ready(function() {
		//channel runtime  requestOperateAuthCode requestAuthCode
	    dd.runtime.permission.requestAuthCode({
	        corpId: _config.corpId,
	        onSuccess: function(result) {
	        	getuserId(result);
	        },
	        onFail : function(err) {
	        	alert("错误"+JSON.stringify(err))
	        }
	 
	    });
	});
	function getuserId(result){
			    //$("body").text('https://oapi.dingtalk.com/user/getuserinfo?code=' + result.code + '&access_token='+ _config.token);
		$.ajax({
			url : '../../dingding/ddEasy',
			type : 'POST',
			data:JSON.stringify({"code":result.code,"token":_config.token}),
			contentType: "application/json; charset=utf-8",
			dataType : "json",
			success : function(suc) {
			    if(suc.status == '1002'){
			    	sessionStorage.setItem("userId",suc.userJson.userid);
			    	sessionStorage.setItem("name",suc.userJson.name);
			    	sessionStorage.setItem("jobnumber",suc.userJson.jobnumber);
			    	sessionStorage.setItem("deptId",suc.userJson.department);
			    	sessionStorage.setItem("mobile",suc.userJson.mobile);
					onload();
			    	
			    }else{
			    	layer.alert(suc.msg);
			    }

			},
			error : function(xhr, errorType, error) {
					alert(errorType + ', ' + error);
				}
		});
	}
	dd.error(function(err) {
		alert('dd error: ' + JSON.stringify(err));
	});
}
dd.error(function(err) {
	layer.closeAll();
	alert('dd error: ' + JSON.stringify(err));
});
function onload(){
	$('#name').text(sessionStorage.getItem("name"));
//	$('#searchButton').on('click',function(){
//		selectShop();
//	});
}
//搜索门店
function selectShop(){
	showloading();
	var sendData = {};
	sendData.latitude=latitude;
	sendData.longitude=longitude;
	sendData.searchValue=$('#pandianShop').val();
	$.ajax({
		url: "getShopWeizhi",
		type : 'POST',
		data:JSON.stringify(sendData),
		contentType: "application/json; charset=utf-8",
		dataType : "json",
		success : function(suc) {
			console.log(suc)
			try {
				if(suc.success){
					var dataArray = suc.data;
//					$('#ss_liebiao').empty();
//					for(var i in dataArray){
//						$('#ss_liebiao').append('<div class="ss_p" onclick="startPandian('+dataArray[i].id+',\''+dataArray[i].shopcode+'\',\''+dataArray[i].shopname+'\','+dataArray[i].flag+',\''+dataArray[i].sEmployeeNO+'\',\''+dataArray[i].sEmployeeName+'\')"><p>'+dataArray[i].shopname+'('+dataArray[i].shopcode+')</p></div>');
//						$('#ss_liebiao').show();
//					}
					addDingwei(dataArray);
				}else{
					layer.msg('没有找到可检查门店的信息')
				}
			} catch (e) {
				console.log(e);
			} finally{
				hideloading();
			}
			
		}
	});
}
//获取检查人所负责门店的最近几家门店
function dingwei(){
	layer.open({type:3,shade:0.3,icon:1,area: ['40px', '40px']});
	var sendData = {};
	sendData.latitude=latitude;
	sendData.longitude=longitude;
//	sendData.notFlag=0;
	$.ajax({
		url: "getShopWeizhi",
		type : 'POST',
		data: JSON.stringify(sendData),
		contentType: "application/json; charset=utf-8",
		dataType : "json",
		success : function(suc) {
			console.log(suc);
			
			try {
				if(suc.success){
					var dataArray = suc.data;
					if(dataArray.length == 0){
						dd.ready(function() {
							dd.device.notification.confirm({
							    message: "您附近没有门店，请先定位门店",
							    title: "提示",
							    buttonLabels: ['返回', '取消'],
							    onSuccess : function(result) {
							    	if(result.buttonIndex == 0){
							    		history.go(-1);
							    	}
							        //onSuccess将在点击button之后回调
							        /*
							        {
							            buttonIndex: 0 //被点击按钮的索引值，Number类型，从0开始
							        }
							        */
							    },
							    onFail : function(err) {}
							});
						});
					}
					addDingwei(dataArray);
				}else{
					layer.msg(suc.message)
				}
			} catch (e) {
				console.log(e);
			} finally{
				layer.closeAll();
			}
			
		 	
		}
	}); 
	//onload();
}
function addDingwei(dataArray){

	$('#shopsDiv').find('.layui-row').remove();
	for (var i = 0; i < dataArray.length; i++) {
		var dis = realdistance(longitude,latitude,dataArray[i].longitude,dataArray[i].latitude).toFixed(2);
		var danwei = "米";
		if(dis >= 1000){
			dis= (dis/1000).toFixed(2);
			danwei ="公里";
		}
		console.log(dataArray[i].shopname+dis);
		var activeClass="";
		if(i==0){
			activeClass = 'address-active';
		}
		
		$('#shopsDiv').append('<div class="layui-row '+activeClass+'" style="">'+
		    '<div class="layui-col-md12 show-address">'+
			    '<i class="material-icons icon iconfont">&#xe66e;</i> '+  
	        	'<span class="til">'+dataArray[i].shopcode+' '+dataArray[i].shopname+'</span>'+
	            '<span class="adder">'+dataArray[i].address+'</span>'+
               	'<span class="range"><font>'+dis+'</font>&nbsp;<font>'+danwei+'</font></span>'+
			'</div>'+
			'<div class="btn_fle_row">'+
		    '<div class="layui-col-xs2 btn next2_1" onclick="startPandian(\''+dataArray[i].shopcode+'\',\''+dataArray[i].shopname+'\',\''+dataArray[i].longitude+'\',\''+dataArray[i].latitude+'\',\''+dataArray[i].address+'\')" id="gocd'+i+'"><a id="caidan'+i+'" href="javascript:void(0)">进入门店</a></div>'+
		    '<div class="layui-col-xs2 btn next2_1" onclick="mendiandaohang(\''+dataArray[i].longitude+'\',\''+dataArray[i].latitude+'\',\''+dataArray[i].shopname+'\')" id="godh'+i+'"><a id="caidan'+i+'" href="javascript:void(0)">门店导航</a></div>'+
		    '</div>'+
		'</div>');
	}
	$(".layui-row").click(function(){
		$(".layui-row").each(function(){
			$(this).removeClass("address-active");
		})
		$(this).addClass("address-active");
	});
}
//高德返回两个经纬度点的距离
function realdistance(longitude,latitude,longitude2,latitude2){
	var lon=Number(longitude);
	var lat=Number(latitude);
	var lnglat1 = new AMap.LngLat(lon, lat);
	var lon2=Number(longitude2);
	var lat2=Number(latitude2);
	var lnglat2 =  new AMap.LngLat(lon2, lat2)
	var dis = lnglat1.distance(lnglat2);
	return dis;
}

//开始盘点
function startPandian(shopcode,shopname,shoplongitude,shoplatitude,shopaddress){

	
	sessionStorage.setItem("shopcode",shopcode);
	sessionStorage.setItem("shopname",shopname);
	sessionStorage.setItem("shoplongitude",shoplongitude);
	sessionStorage.setItem("shoplatitude",shoplatitude);
	sessionStorage.setItem("shopaddress",shopaddress);
	showloading();
	var sendData = {};
	sendData.shopcode=shopcode;
	sendData.shopname=shopname;
	sendData.shoplongitude=shoplongitude;
	sendData.shoplatitude=shoplatitude;
	sendData.shopaddress=shopaddress;
	sendData.latitude=latitude;
	sendData.longitude=longitude;
	sendData.address=address;
	sendData.remark = '';
	sendData.flag = 0
	sendData.imgurl = [];
	sendData.userId=sessionStorage.getItem("userId");
	$.ajax({
		url: "insertHuodong_jiancha_jd_every",
		type : 'POST',
		data:JSON.stringify(sendData),
		contentType: "application/json; charset=utf-8",
		dataType : "json",
		success : function(suc) {
			console.log(suc)
			try {
				if(suc.success){
					window.location.href='toHuodong_jiancha_jd_item?everyId='+suc.data.everyId;
				}else{
					layer.msg(suc.message)
				}
			} catch (e) {
				console.log(e);
			} finally{
				hideloading();
			}
			
		}
	});
}
function mendiandaohang(longitude,latitude,shopname){
	dd.biz.map.view({
	    latitude: latitude, // 纬度
	    longitude: longitude, // 经度
	    title: shopname // 地址/POI名称
	});
}
